<template>
  <!-- 多选组件 -->
  <el-select
    v-model="data"
    multiple
    clearable
    filterable
    :placeholder="this.placeholder"
    @change="handleOptionClick"
    @remove-tag="handleRemoveItem"
    style="width: 240px"
  >
    <el-option
      v-for="item in this.options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      @click="toClickHandleitem(item)"
    />
  </el-select>

  <span id="selectAllOrNone" @click="selectAllOrNone">全选</span>
</template>

<script>
import { defineComponent } from "vue";
export default defineComponent({
  props: {
    modelData: {
      type: Array,
      default: () => [],
    },
    placeholder: {
      type: String,
      default: "",
    },
    //初始化options
    options: {
      type: Array,
      default: () => [],
    },
  },
  emit: ["update:modelData", "getOption", "changeServiceType"],
  data() {
    return {
      isSelectAll: false, //作为标记是否全部选中
    };
  },
  computed: {
    data: {
      get() {
        return this.modelData;
      },
      set(val) {
        this.$emit("update:modelData", val);
      },
    },
  },
  methods: {
    /**
     * 返回选择的option
     * @param {object} data - 选择的option
     */
    handleOptionClick(data) {
      this.$emit("getOption", data);
    },
    clearModelData() {
      this.data = "";
      this.$emit("update:modelData", "");
    },
    toClickHandleitem(item) {},
    handleRemoveItem(e) {
      // e代表移除项的value值
      this.data = this.data.filter((item) => item != e);
    },
    selectAllOrNone() {
        let arr2 = this.options.map(item => item.value)
        if (this.data.length<this.options.length) {
            this.$emit('update:modelData', this.data.concat(this.getUniqueObjects(arr2,this.data)))
            this.$emit('changeServiceType', this.data.concat(this.getUniqueObjects(arr2,this.data)))   
        }
    },
    getUniqueObjects(arr1, arr2) {
        const set2 = new Set(arr2.map(JSON.stringify));
        return arr1.filter(obj1 => {
            const str = JSON.stringify(obj1);
            return !set2.has(str);
        });
    }
  },
  mounted() {},
});
</script>

<style lang="scss" scope>
#selectAllOrNone {
  color: #5a99e7;
  margin-left: 12px;
}
#selectAllOrNone:hover {
  cursor: pointer;
}
</style>
